package com.lhz;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author lihuazhi
 */
@Component
@Slf4j
public class JobApplicationContext implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    /**
     * 得到spring的IOC容器
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (JobApplicationContext.applicationContext == null) {
            JobApplicationContext.applicationContext = applicationContext;
        }
        log.info("JobApplicationContext 配置成功,applicationCont ext对象：" + JobApplicationContext.applicationContext);
    }

    /**
     * 通过bean名称获取bean实例
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    /**
     * 通过bean类型获取bean实例
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 通过bean名称和类型获取bean实例
     *
     * @param name  bean名称
     * @param clazz bean类型
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }
}